import axios from 'axios';
import store from '@/store'
import router from '@/router';
import { Modal } from 'ant-design-vue';
import storage from 'store'

import { ACCESS_INFO, ACCESS_TOKEN } from '@/store/mutation-types';
import {VueAxios} from './axios';
import { AESEncrypt } from '@/utils/utils';

// 创建 axios 实例
console.log(process.env.VUE_APP_USE_MOCK);
const service = axios.create({
  baseURL: process.env.VUE_APP_USE_MOCK == true ? '/mock' : process.env.VUE_APP_SERVER_URL, // api base_url
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

const err = (error) => {
  console.log(error.response.status);
  if (error.response) {
    const { data } = error.response;
    // const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      Modal.error({ title: data.errorMsg });
    }
    if (error.response.status === 401) {
        store.dispatch('Logout').then(() => {
            router.replace({path: sessionStorage.getItem('paths') || '/auth/login' })
        })
    }
  }

  return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use((Config) => {
  const config = Config;
  const info = storage.get(ACCESS_INFO);
  if (info) {
    config.headers['X-Access-Token'] = AESEncrypt(storage.get(ACCESS_TOKEN));
    config.headers['X-Access-UserId'] = AESEncrypt(info.uid);
    // config.headers.Authorization = token; // 如果有 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config;
}, err);

// response interceptor
service.interceptors.response.use((response) => response, err);

const installer = {
  vm: {},
  // eslint-disable-next-line no-shadow
  install(Vue) {
    Vue.use(VueAxios, service);
  }
};

export {
  installer as VueAxios,
  service as axios
};
